var uploader = {
    'data':{
        'token':'',
        'uploadDomain':'',
        'domain':''
    },
    //  上传成功后的回调.
    'complete':function(res){
        console.dir(res);
        console.dir(res['x:origin_object'].get(0));
        // 这里只需要res.key
        var url=uploader.data.domain +"/"+ res.key;
    },
    // 上传时的错误.
    'error':function () {
        console.dir(arguments);
    },
    // 分片上传时的进度展示功能在此书写.
    'next':function (response) {
        // var chunks = response.chunks || [];
        // var total = response.total;
    },
    // 初始化获取token.
    'init':function(){
        $.ajax({
            'url':'/upload/get-token',
            'type':'POST',
            'dataType':'json',
            'success':function(data){
                if(data.code != 200)
                {
                    layer.alert(data.msg);
                    return false;
                }
                uploader.data.token = data.data.token;      // token
                uploader.data.domain = data.data.domain;    // 显示域名
                // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
                console.log(uploader.data.domain)
            }
        });
    },
    'eventBind':function(){
        this.init();
        $('.default').on('change',function () {
            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };

            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };

            var file = this.files[0];

            var observable;

            if (file) {
                var files=$(".default")[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                console.log(key)
                putExtra.params["x:name"] = key.split(".")[0];
                // putExtra.params['x:origin_object'] = $('.default').attr('id');
                putExtra.params['x:origin_object'] = $('.default');
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });
    }
};

$(document).ready(function(){
    uploader.eventBind();
});
